<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="12">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item :label="$t('f_商品信息')" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input :placeholder="$t('请输入商品编码/名称/条码')" v-model="queryParam.goodsInfo"></a-input>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="5" :lg="6" :md="7" :sm="24">
              <a-form-item :label="$t('f_上架状态')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-select v-model="queryParam.state" @change="handleChange">
                  <a-select-option value="">{{ $t('全部') }}</a-select-option>
                  <a-select-option value="Y">{{ $t('是') }}</a-select-option>
                  <a-select-option value="N">{{ $t('否') }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('销售兑换方式')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-select v-model="sales" @change="handleChangeSales">
                  <a-select-option value="">{{ $t('全部') }}</a-select-option>
                  <a-select-option value="allowAlottery">{{ $t('允许A票兑换') }}</a-select-option>
                  <a-select-option value="allowCoin">{{ $t('允许币兑换') }}</a-select-option>
                  <a-select-option value="allowIntegral">{{ $t('允许积分兑换') }}</a-select-option>
                  <a-select-option value="allowLottery">{{ $t('允许彩票兑换') }}</a-select-option>
                  <a-select-option value="allowMemberDiscount">{{ $t('允许享受会员优惠') }}</a-select-option>
                  <a-select-option value="allowOut">{{ $t('允许0库存出库') }}</a-select-option>
                  <a-select-option value="allowPoints">{{ $t('允许A币兑换') }}</a-select-option>
                  <a-select-option value="allowSale">{{ $t('允许销售') }}</a-select-option>
                  <a-select-option value="allowWarn">{{ $t('开启缺货提示') }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('券类型')">
                <a-select v-model="queryParam.couponType" @change="handleChange">
                  <a-select-option :value="item.value" v-for="(item,i) in dictOptions.typeList" :key="i">{{ item.text }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">{{ $t('查询') }}</a-button>
              <a-button type="primary" @click="handleReset" icon="reload" style="margin-left: 8px">{{
                $t('重置')
              }}</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? $t('收起') : $t('展开') }}<a-icon :type="toggleSearchStatus ? 'up' : 'down'"
              /></a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus" v-has="'BisGoodsInforController:add'">{{ $t('新增') }}</a-button>
    </div>
    <div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        bordered
        rowKey="id"
        class="j-table-force-nowrap"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">{{ $t('无图片') }}</span>
          <img v-for="(item,i) in text.split(',')" :key="i"
            v-else
            :src="getImgView(text)"
            height="25px"
            alt=""
            style="max-width: 80px; font-size: 12px; font-style: italic;margin-right:5px"
          />
        </template>
        <span slot="action" slot-scope="text, record">
          <a-popconfirm
            v-if="record.state == 'Y'"
            :title="$t('确定下架吗?')"
            @confirm="() => changeStatus(record.id, record.state)"
          >
            <a v-has="'BisGoodsInforController:edit'">{{ $t('下架') }}</a>
          </a-popconfirm>
          <a-popconfirm
            v-if="record.state == 'N'"
            :title="$t('确定上架吗?')"
            @confirm="() => changeStatus(record.id, record.state)"
          >
            <a>{{ $t('上架') }}</a> </a-popconfirm
          >&nbsp;&nbsp;
          <span>
            <a @click="handleEdit(record)" v-has="'BisGoodsInforController:edit'">{{ $t('编辑') }}</a>
          </span>
          &nbsp;&nbsp;
          <a-popconfirm :title="$t('确定删除吗?')" @confirm="() => handleDelete(record.id)">
            <a v-has="'BisGoodsInforController:delete'">{{ $t('删除') }}</a>
          </a-popconfirm>
          &nbsp;&nbsp;
          <span>
            <a @click="handleEdit(record, true)">{{ $t('详情') }}</a>
          </span>
        </span>

        <div slot="sort" slot-scope="text, record">
          <div v-for="col in ['sort']" :key="col" style="display: flex; justify-content: center">
            <div>
              <a-input
                v-if="record.editable"
                style="margin: -5px 0; padding: 0; width: 50px"
                :value="text"
                @change="(e) => handleChange(e.target.value, record.id, col)"
                :maxLength="3"
              />
              <template v-else>{{ text }}</template>
            </div>
            <div class="editable-row-operations">
              <span v-if="record.editable">
                <a @click="() => save(record.id)"><a-icon type="save" /></a>
              </span>
              <span v-else>
                <a :disabled="editingKey !== ''" @click="() => edit(record.id)"><a-icon type="edit" /></a>
              </span>
            </div>
          </div>
        </div>
      </a-table>
    </div>
    <coupon-setting-modal :infoData="info" ref="modalForm" @ok="modalFormOk"></coupon-setting-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import Vue from 'vue'
import { getAction, putAction, getFileAccessHttpUrl, deleteAction } from '@/api/manage'
import { initDictOptions, filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import CouponSettingModal from '../goods/modules/CouponsModal'

export default {
  name: 'CouponSetting',
  components: {
    CouponSettingModal,
  },
  data() {
    return {
      loading: false,
      dataSource: [],
      info: {
        disable: true,
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 },
      },
      description: '优惠券设置管理页面',
      editingKey: '',
      index: 0,
      operation: false,
      queryParam: {
        column: 'sort',
        order: 'asc',
        goodsInfo: '',
        state: '',
        notSystem: 1,
        form: 9,
        couponType: ''
      },
      sales: '',
      dialogFormVisible: false,
      //列设置
      settingColumns: [],
      // 表头
      columns: [
        {
          title: this.$t('排序'),
          dataIndex: 'sort',
          align: 'center',
          scopedSlots: { customRender: 'sort' },
          customCell: () => {
            return {
              style: {
                width: '80px',
              },
            }
          },
        },
        {
          title: this.$t('商品形态'),
          align: 'center',
          dataIndex: 'form_dictText',
        },
        {
          title: this.$t('商品编码'),
          align: 'center',
          dataIndex: 'code',
        },
        {
          title: this.$t('商品名称'),
          align: 'center',
          dataIndex: 'name',
        },
        {
          title: this.$t('券类型'),
          align: 'center',
          dataIndex: 'couponType_dictText',
        },
        {
          title: this.$t('商品分类'),
          align: 'center',
          dataIndex: 'kindName',
        },
        {
          title: this.$t('上架状态'),
          align: 'center',
          dataIndex: 'state',
          customRender: (text) => (text ? filterMultiDictText(this.dictOptions['state'], text) : ''),
        },
        {
          title: this.$t('是否允许销售'),
          align: 'center',
          dataIndex: 'allowSale',
          customRender: (text) => (text ? filterMultiDictText(this.dictOptions['allowSale'], text) : ''),
        },
        {
          title: this.$t('售价'),
          align: 'center',
          dataIndex: 'price',
          customCell: () => {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          customRender: (text, r) => {
            text = (text ==null || text =="" || text ==undefined)?0:parseFloat(text);
            return text.toFixed(2);
          }
        },
        {
          title: this.$t('商品图片'),
          align: 'center',
          dataIndex: 'picture',
          scopedSlots: { customRender: 'imgSlot' },
        },
        {
          title: this.$t('操作'),
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/goods/bisGoodsInfor/list',
        delete: '/goods/bisGoodsInfor/delete',
        exportXlsUrl: '/goods/bisGoodsInfor/exportXls',
        importExcelUrl: 'sys/common/upload',
      },
      dictOptions: {},
      superFieldList: [],
      typeNameForm: false,
      sortData: [],
      sortId: 0,
      tableColumns: [],
      secCols: [],
      pageName: this.$t('卖品资料管理'),
      list: [],
      rootItem: {},
      totalSize: 0,

      batchList: [],
      ipagination: {
        current: 1,
        pageSize: 30,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + this.$t('sum-total', { total: total })
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
        onShowSizeChange: (current, pageSize) => this.handleSizeChange(current, pageSize),
      },
      toggleSearchStatus: true,
    }
  },
  created() {
    initDictOptions('bis_goods_infor.coupon_type').then((res) => {
      if (res.success) {
        this.$set(this.dictOptions, 'typeList', res.result)
        this.dictOptions.typeList.unshift({ value: '', text: this.$t('全部') })
      }
    })
    this.$set(this.dictOptions, 'allowOut', [
      { text: this.$t('是'), value: 'Y' },
      { text: this.$t('否'), value: 'N' },
    ])
    this.$set(this.dictOptions, 'state', [
      { text: this.$t('是'), value: 'Y' },
      { text: this.$t('否'), value: 'N' },
    ])
    this.$set(this.dictOptions, 'allowWarn', [
      { text: this.$t('是'), value: 'Y' },
      { text: this.$t('否'), value: 'N' },
    ])
    this.$set(this.dictOptions, 'allowSale', [
      { text: this.$t('是'), value: 'Y' },
      { text: this.$t('否'), value: 'N' },
    ])
    this.$set(this.dictOptions, 'allowIntegral', [
      { text: this.$t('是'), value: 'Y' },
      { text: this.$t('否'), value: 'N' },
    ])
    this.$set(this.dictOptions, 'allowCoin', [
      { text: this.$t('是'), value: 'Y' },
      { text: this.$t('否'), value: 'N' },
    ])
    this.$set(this.dictOptions, 'allowLottery', [
      { text: this.$t('是'), value: 'Y' },
      { text: this.$t('否'), value: 'N' },
    ])
    this.$set(this.dictOptions, 'allowAlottery', [
      { text: this.$t('是'), value: 'Y' },
      { text: this.$t('否'), value: 'N' },
    ])
    this.$set(this.dictOptions, 'allowPoints', [
      { text: this.$t('是'), value: 'Y' },
      { text: this.$t('否'), value: 'N' },
    ])
    this.$set(this.dictOptions, 'allowMemberDiscount', [
      { text: this.$t('是'), value: 'Y' },
      { text: this.$t('否'), value: 'N' },
    ])
    this.searchQuery()
  },
  watch: {},
  computed: {
    tokenHeader() {
      let head = { 'X-Access-Token': Vue.ls.get(ACCESS_TOKEN) }
      let tenantid = Vue.ls.get(TENANT_ID)
      if (tenantid) {
        head['tenant-id'] = tenantid
      }
      return head
    },
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    initDictConfig() {},
    handleSizeChange(current, pageSize) {
      this.ipagination.pageSize = pageSize
    },
    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },
    getGoodsList(num) {
      let that = this
      let querydata = {}
      that.ipagination.current = num
      that.queryParam.pageNo = that.ipagination.current
      that.queryParam.pageSize = that.ipagination.pageSize
      querydata = that.queryParam
      this.loading = true
      getAction('/goods/bisGoodsInfor/list', querydata)
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records
            this.dataSource.forEach((col) => {
              if (col.validityType == '0') {
                col.validityType_text = this.$t('不限期')
              } else if (col.validityType == '1') {
                col.validityType_text = col.startDate + '~' + col.endDate
              } else {
                col.validityType_text =
                  this.$t('领取后') + col.startDays + this.$t('天生效，有效期') + col.validDays + this.$t('天')
              }
            })
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    clickBatchEdit() {
      if (this.batchList.length > 0) {
        this.$refs.modalForm1.edit(this.batchList)
      } else {
        this.$message.warning(this.$t('请选择需要批量修改的商品'))
      }
    },
    modalFormOk() {
      this.getGoodsList(1)
    },
    searchQuery() {
      this.getGoodsList(1)
      this.editingKey = ''
    },
    edit(id) {
      let that = this
      const newData = [...that.dataSource]
      const target = newData.filter((item) => id === item.id)[0]
      this.editingKey = id
      if (target) {
        target.editable = true
        this.dataSource = newData
      }
    },
    save(id) {
      let that = this
      const newData = [...that.dataSource]
      const target = newData.filter((item) => id === item.id)[0]
      if (target) {
        delete target.editable
        let goods = {
          id: target.id,
          sort: target.sort
        }
        putAction('/goods/bisGoodsInfor/editSort', goods)
          .then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.getGoodsList(1)
            } else {
              that.$message.warning(res.message)
            }
          })
      }
      that.editingKey = ''
    },
    handleChangeSales() {
      delete this.queryParam.allowAlottery
      delete this.queryParam.allowCoin
      delete this.queryParam.allowIntegral
      delete this.queryParam.allowLottery
      delete this.queryParam.allowMemberDiscount
      delete this.queryParam.allowOut
      delete this.queryParam.allowPoints
      delete this.queryParam.allowSale
      delete this.queryParam.allowWarn
      switch (this.sales) {
        case 'allowAlottery':
          this.queryParam.allowAlottery = 'Y'
          break
        case 'allowCoin':
          this.queryParam.allowCoin = 'Y'
          break
        case 'allowIntegral':
          this.queryParam.allowIntegral = 'Y'
          break
        case 'allowLottery':
          this.queryParam.allowLottery = 'Y'
          break
        case 'allowMemberDiscount':
          this.queryParam.allowMemberDiscount = 'Y'
          break
        case 'allowOut':
          this.queryParam.allowOut = 'Y'
          break
        case 'allowPoints':
          this.queryParam.allowPoints = 'Y'
          break
        case 'allowSale':
          this.queryParam.allowSale = 'Y'
          break
        case 'allowWarn':
          this.queryParam.allowWarn = 'Y'
          break
      }
    },

    handleChange(value, id, column) {
      const newData = [...this.dataSource]
      const target = newData.filter((item) => id === item.id)[0]
      if (target) {
        target[column] = value
        this.dataSource = newData
      }
    },
    changeStatus(id, state) {
      if (state == 'Y') {
        state = 'N'
      } else if (state == 'N') {
        state = 'Y'
      }
      putAction('/goods/bisGoodsInfor/edit', { id: id, state: state }).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.getGoodsList(1)
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    showModal(record) {
      this.typeNameForm = true
      this.info = record
    },
    changeModalVisible() {
      this.typeNameForm = false
    },
    handleAdd(state, record) {
      this.$refs.modalForm.title = this.$t('新增优惠券')
      this.$refs.modalForm.add()
    },
    handleEdit(record, state) {
      this.$refs.modalForm.edit(record, state)
      this.$refs.modalForm.title = this.$t('编辑')
      this.$refs.modalForm.disableSubmit = false
    },
    handleDelete(id) {
      if (!this.url.delete) {
        this.$message.error(this.$t('请设置url.delete属性'))
        return
      }
      var that = this
      deleteAction(that.url.delete, { id: id }).then((res) => {
        if (res.success) {
          //重新计算分页问题
          that.reCalculatePage(1)
          that.$message.success(res.message)
          that.getGoodsList(1)
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      this.getGoodsList(pagination.current)
    },
    handleReset() {
      this.queryParam = {
        column: 'sort',
        order: 'asc',
        goodsInfo: '',
        state: '',
        notSystem: 1,
        form: 9,
        couponType: ''
      }
      this.sales = ''
      this.getGoodsList(1)
    },
    editGoods(row, opet) {
      let that = this
      that.dialogFormVisible = true
    },
    getImgView(text) {
      if (text && text.indexOf(',') > 0) {
        text = text.substring(0, text.indexOf(','))
      }
      return getFileAccessHttpUrl(text)
    },
    reCalculatePage(count) {
      //总数量-count
      let total = this.ipagination.total - count
      //获取删除后的分页数
      let currentIndex = Math.ceil(total / this.ipagination.pageSize)
      //删除后的分页数<所在当前页
      if (currentIndex < this.ipagination.current) {
        this.ipagination.current = currentIndex
      }
    },
    getQueryField() {
      //TODO 字段权限控制
      var str = 'id,'
      this.columns.forEach(function (value) {
        str += ',' + value.dataIndex
      })
      return str
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>